package com.xxxx.work.rr.recv;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * 工作队列（轮询）-消息消费者
 */
public class Recv02 {

    // 定义队列
    private final static String QUEUE_NAME = "work_rr";

    public static void main(String[] argv) throws Exception {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // rabbitmq服务开启的虚拟机地址
        factory.setHost("192.168.1.105");
        // 登录rabbitmq的用户名、密码
        factory.setUsername("yeb");
        factory.setPassword("yeb");
        // 虚拟地址
        factory.setVirtualHost("/yeb");
        // 端口号
        factory.setPort(5672);

        // 连接工厂创建连接
        Connection connection = factory.newConnection();
        // 创建信道
        Channel channel = connection.createChannel();

        //
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            try {
                // 模拟消费耗时
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
            /**
             * 手动确认
             * multiple:是否确认多条
             */
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        // 监听队列消费消息，autoAck改为false，手动确认，还需要加个手动确认的代码
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }
}